<script lang="ts" setup>

import {computed, reactive} from "vue";
import { isEmpty } from 'lodash';
const props = defineProps({
  message: {
    type: String,
    default: "",
  },
  show: {
    type: Boolean,
    default: false,
  },
  goodsInfo: {
    type: Array,
    default: [],
  }
});



const state = reactive({
  selectedSkuPrice: {}, // 选中的sku价格-这里是对象是goodsInfo.sku_prices选中的一项，真正的价格是这个对象的price
  materialsPrice: 0, // 加料价格
  currentSkuArray: [],// 选中的sku
  currentMateArray: [], // 选中的加料
  material_index:'', // 选中的加料
  materialTextArr:[],
  goods_num:1, // 商品数量
});


// 可选规格
const skuPrices = computed(() => {
  let skuPrices = props.goodsInfo.sku_prices;
  if (props.goodsInfo.is_sku) {
    skuPrices.forEach((item) => {
      item.goods_sku_id_arr = item.goods_sku_ids.split(',');
    });
  }
  return skuPrices;
});

const snapshot_description = computed(() => {
  //state.selectedSkuPrice.goods_sku_text 为 undefined 或 {0: '中杯', 1: '测试1'}
  // 合并goods_sku_text和materialTextArr
  let arr = [];
  if (state.selectedSkuPrice.goods_sku_text) {
    arr = arr.concat(Object.values(state.selectedSkuPrice.goods_sku_text));
  }
  if (state.materialTextArr.length) {
    arr = arr.concat(state.materialTextArr);
  }
  return arr.join(',');
})

const emit = defineEmits(["close", "confirm"]);

const closeGoodDetailModal = () => {
  emit("close"); // 或者 emit('delete', 123);
};
const handleAddToCartInModal = () => {
  emit("confirm",{
    goods_id: props.goodsInfo.id,
    goods_sku_price_id: state.selectedSkuPrice.id,
    material_index: state.material_index,
    goods_num: state.goods_num,
    type: 'cover'
  }); // 或者 emit('delete', 123);
};

// 当前所选规格下，获取所有有库存的 skuPrice
function getCanUseSkuPrice() {
  let newPrice = [];
  for (let price of skuPrices.value) {
    var isOk = true;
    state.currentSkuArray.forEach((sku) => {
      // sku 不为空，并且，这个 条 skuPrice 没有被选中,则排除
      if (sku.toString() != '' && price.goods_sku_id_arr.indexOf(sku.toString()) < 0) {
        isOk = false;
      }
    });
    if (isOk) {
      newPrice.push(price);
    }
  }
  return newPrice;
}

function onSelectSku(pid:number , skuId:number ) {
  let isChecked = true; // 选中 or 取消选中
  if (state.currentSkuArray[pid] != undefined && state.currentSkuArray[pid] == skuId) {
    // 点击已被选中的，删除并填充 ''
    isChecked = false;
    state.currentSkuArray.splice(pid, 1, '');
  } else {
    // 选中
    state.currentSkuArray[pid] = skuId;
  }
  let chooseSkuId = [];
  state.currentSkuArray.forEach((sku) => {
    if (sku != '') {
      // sku 为空是反选 填充的
      chooseSkuId.push(sku);
    }
  });
  // 当前所选规格下，所有可以选择的 skuPric
  let newPrice = getCanUseSkuPrice();
  const skuList = props.goodsInfo.skus;
  // 判断所有规格大类是否选择完成
  if (chooseSkuId.length == skuList.length && newPrice.length) {
    state.selectedSkuPrice = newPrice[0];
  } else {
    state.selectedSkuPrice = {};
  }
  console.log(">>>>state.selectedSkuPrice",state.selectedSkuPrice.goods_sku_text);
}
function onSelectMate(pid:number , mateId:number ) {
  if (state.currentMateArray[pid] != undefined && state.currentMateArray[pid] == mateId) {
    // 点击已被选中的，删除并填充 ''
    state.currentMateArray.splice(pid, 1, '');
  } else {
    // 选中
    state.currentMateArray[pid] = mateId;
  }
  // material_index 处理成 1::1,2::5 格式 pid::mateId
  let result = [];
  state.currentMateArray.forEach((item, index) => {
    if (item !== '') {
      result.push(`${index}::${item}`);
    }
  });
  state.material_index = result.join(','); // 如 "0::a,2::c"

  // 计算加料价格
  let materialsPrice = 0;
  const mateList= props.goodsInfo.materials_info;
  //选中的加料有价格，增加价格
  state.materialTextArr = [];
  mateList.forEach((item) => {
    item.items.forEach((mate) => {
      if (state.currentMateArray[item.category.id] == mate.id) {
        materialsPrice += mate.price;
        state.materialTextArr.push(`${mate.name}`);
      }
    });
  })
  state.materialsPrice = materialsPrice;
}
// 获取商品的价格-计算属性
const goodsPrice = computed(() => {
  let price;
  if (isEmpty(state.selectedSkuPrice)) {
    price = parseFloat(props.goodsInfo.price) || 0;
  } else {
    price = parseFloat(state.selectedSkuPrice.price) || 0;
  }

  const materialsPrice = parseFloat(state.materialsPrice) || 0;
  return (price + materialsPrice).toFixed(2);
});


const handlePropertyReduce=()=>{
  if(state.goods_num>1){
    state.goods_num--;
  }
}
const handlePropertyAdd=()=>{
  state.goods_num++;
}

</script>

<template>
  <u-modal
    :show="show"
    class="good-detail-modal"
    color="#5A5B5C"
    width="650rpx"
    custom
    padding="0rpx"
    radius="12rpx"
    @confirm="handleAddToCartInModal"
    @close="closeGoodDetailModal"
    confirmText="加入购物车"
    confirmColor="#f0ad4e"
  >
    <view class="modal-content">
      <view class="cover">
        <u-image
          width="260rpx"
          height="260rpx"
          :src="goodsInfo.image_url"
          class="image"
        ></u-image>
        <view class="btn-group">
          <up-icon
            @click="closeGoodDetailModal"
            name="close"
            color="#2979ff"
            size="28"
          ></up-icon>
        </view>
      </view>
      <scroll-view class="detail" scroll-y>
        <view class="wrapper">
          <view class="basic">
            <view class="name">{{ goodsInfo.name }}</view>
            <view class="tips">
              {{ goodsInfo.content }}
            </view>
          </view>
          <view class="properties">
            <view
              class="property"
              v-for="sku1 in goodsInfo.skus"
              :key="sku1.id"
            >
              <view class="title">
                <text class="name">{{ sku1.name}}</text>
              </view>
              <view class="values">
                <view
                  class="value"
                  v-for="sku2 in sku1.children"
                  :key="sku2.id"
                  :class="[{
                    'default': state.currentSkuArray[sku2.parent_id] == sku2.id,
                  }]"
                  @tap="onSelectSku(sku2.parent_id, sku2.id)"
                >
                  {{ sku2.name }}
                </view>
              </view>
            </view>
            <view
                class="property"
                v-for="mate1 in goodsInfo.materials_info"
                :key="mate1.category.id"
            >
              <view class="title">
                <text class="name">{{ mate1.category.name}}</text>
              </view>
              <view class="values">
                <view
                    class="value"
                    v-for="mate2 in mate1.items"
                    :key="mate2.id"
                    :class="[{
                    'default': state.currentMateArray[mate1.category.id] == mate2.id,
                  }]"
                    @tap="onSelectMate(mate1.category.id, mate2.id)"
                >
                  {{ mate2.name }} {{ mate2.price>0 ? '￥' + mate2.price  : '' }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>

      <view class="action">
        <view class="left">
          <view class="price">￥{{ goodsPrice }}</view>
          <view class="props"> {{ snapshot_description }}</view>
        </view>
        <view class="btn-group">
          <up-icon
            @click="handlePropertyReduce"
            name="minus-circle"
            size="20"
            color="#999"
          ></up-icon>
          <view class="number">{{ state.goods_num }}</view>
          <up-icon
            name="plus-circle-fill"
            size="20"
            color="#f0ad4e"
            @click="handlePropertyAdd"
          ></up-icon>
        </view>
      </view>
    </view>
  </u-modal>
</template>


<style lang="scss" scoped>
.good-detail-modal {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .modal-content {
    width: 100%;
    flex-direction: column;
  }

  .cover {
    width: 100%;
    height: 320rpx;
    padding: 30rpx 0;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;

    .image {
      width: 260rpx;
      height: 260rpx;
    }

    .btn-group {
      position: absolute;
      right: 10rpx;
      top: 30rpx;
      display: flex;
      align-items: center;
      justify-content: space-around;

      image {
        width: 80rpx;
        height: 80rpx;
      }
    }
  }

  .detail {
    width: 100%;
    min-height: 1vh;
    max-height: calc(68vh - 320rpx - 80rpx - 120rpx);

    .wrapper {
      width: 100%;
      height: 100%;
      overflow: hidden;

      .basic {
        padding: 0 20rpx 30rpx;
        display: flex;
        flex-direction: column;

        .name {
          font-size: $uni-font-size-base;
          color: $uni-text-color;
          margin-bottom: 10rpx;
        }

        .tips {
          font-size: $uni-font-size-sm;
          color: $uni-text-color-grey;
        }
      }

      .properties {
        width: 100%;
        //border-top: 2rpx solid $uni-bg-color-grey;
        padding: 10rpx 30rpx 0;
        display: flex;
        flex-direction: column;

        .property {
          width: 100%;
          display: flex;
          flex-direction: column;
          margin-bottom: 30rpx;
          padding-bottom: -16rpx;

          .title {
            width: 100%;
            display: flex;
            justify-content: flex-start;
            align-items: center;
            margin-bottom: 20rpx;

            .name {
              font-size: 26rpx;
              //color: $uni-text-color;
              margin-right: 20rpx;
            }

            .desc {
              flex: 1;
              //font-size: $font-size-sm;
              //color: $uni-color-primary;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }

          .values {
            width: 100%;
            display: flex;
            flex-wrap: wrap;

            .value {
              border-radius: 8rpx;
              background-color: $uni-bg-color-grey;
              padding: 16rpx 30rpx;
              font-size: 26rpx;
              //	color: $uni-text-color-assist;
              margin-right: 16rpx;
              margin-bottom: 16rpx;

              &.default {
                background-color: $uni-color-warning;
                color: #fff;
              }
            }
          }
        }
      }
    }
  }

  .action {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: $uni-bg-color-grey;
    height: 120rpx;
    padding: 0 26rpx;

    .left {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      margin-right: 20rpx;
      // overflow: hidden;

      .price {
        //font-size: $uni-font-size-lg;
        color: $uni-text-color;
      }

      .props {
        color: $uni-text-color;
        font-size: 20rpx;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .btn-group {
      display: flex;
      align-items: center;
      justify-content: space-around;

      .number {
        //font-size: $uni-font-size;
        width: 44rpx;
        height: 44rpx;
        line-height: 44rpx;
        text-align: center;
      }

      .btn {
        padding: 0;
        //font-size: $uni-font-size;
        width: 44rpx;
        height: 44rpx;
        line-height: 44rpx;
        border-radius: 100%;
      }
    }
  }

  .add-to-cart-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: $uni-color-primary;
    //color: $uni-text-color-white;
    font-size: $uni-font-size-base;
    height: 80rpx;
    border-radius: 0 0 12rpx 12rpx;
  }
}
</style>